<template>
	<view class="family-container">
		<!-- 顶部选项卡 -->
		<!-- <view class="tab-header">
			<view 
				v-for="(tab, index) in tabs" 
				:key="index"
				:class="['tab-item', { active: currentTab === index }]"
				@click="switchTab(index)"
			>
				{{ tab.name }}
			</view>
		</view> -->

		<!-- 顶部搜索框 -->
		<view class="header">
			<view class="backBtn" v-if="currentTab == 1" @click="switchTab(0)">
				返回
			</view>
			<view class="search-box">
				<image src="/static/search.png" class="search-icon"></image>
				<input type="text" :placeholder="currentTab === 0 ? '请输入用户姓名或手机号码' : '请输入户主姓名或手机号码'"
					placeholder-class="placeholder-style" v-model="state.searchText" @input="handleSearch" />

			</view>
			<view class="logout-btn" @click="logout" v-if="currentTab == 0">
				<image src="/static/logout.png" class="logout-icon"></image>
				<view>登出</view>
			</view>
		</view>

		<view class="body">
			<!-- 添加成员按钮 -->
			<view class="add-member" v-if="currentTab === 1" @click="addMembr">
				<view class="add-icon">+</view>
				<view class="add-text">
					<view class="title">添加家庭成员</view>
					<view class="subtitle">最多可添加10位家人</view>
				</view>
			</view>

			<!-- 列表区域 -->
			<view class="member-list">
				<view v-if="currentTab == 0">
					<!-- 用户列表样式 -->
					<view class="user-item" v-for="(item, index) in state.showData" :key="index">
						<view class="user-avatar">
							<image src="/static/homeHead.png"></image>
							<!-- <text class="gender-icon">{{ item.sex === '男' ? '♂' : '♀' }}</text> -->
						</view>
						<view class="user-info">
							<view class="name">{{ item.person_name }}</view>
							<view class="phone">{{ item.phone }}</view>
							<view class="address">{{ item.address }}</view>
						</view>
						<view class="btnBox">
							<view class="detailBtn" @click="getFamilyList(item._id)">
								所属用户
							</view>
							<view class="redemptionBtn" @click="toRedemption(item._id)">
								兑换记录
							</view>
							<view class="walltBtn" @click="toWallet(item)">
								积分列表
							</view>
						</view>
					</view>
				</view>

				<view v-else>
					<!-- 户籍列表样式 -->
					<view class="member-item" v-for="(item, index) in state.showData" :key="index"
						@touchstart="(e) => touchStart(e, index)" @touchmove="touchMove" @touchend="touchEnd"
						:style="{ transform: `translateX(${item.offset || 0}px)` }">
						<view class="avatar">
							<image src="/static/personHead.png"></image>
						</view>
						<view class="member-info">
							<view class="name">{{ item.family_person_name }}</view>
							<view class="tag">{{ getOptionLabel(item.family_person_type, state.relationList) }}</view>
							<view class="phone">{{ item.family_person_phone }}</view>
						</view>
						<view class="delete-btn" @click="delMember(item._id)">
							<image src="/static/del.png" class="deleteIcon"></image>
						</view>
					</view>
				</view>
			</view>
		</view>

		<custom-tabbar currentPath="/pages/domicile/domicile"></custom-tabbar>
	</view>
</template>

<script setup>
import {
	ref,
	reactive,
	computed
} from 'vue';
import CustomTabbar from '@/components/custom-tabbar/custom-tabbar.vue'
import {
	onShow
} from '@dcloudio/uni-app';
import {
	request,
	getOptionLabel
} from "../../js/util.js";
// 选项卡配置
const tabs = [{
	name: '用户列表'
},
{
	name: '户籍列表'
}
];
const currentTab = ref(0);

const state = reactive({
	currentFamily: "",
	showData: [],
	userId: "",
	searchText: '',
	userList: [], // 用户列表数据
	familyList: [], // 户籍列表数据
	relationList: [{
		label: "本人",
		value: 0
	},
	{
		label: "配偶",
		value: 1
	},
	{
		label: "父母",
		value: 2
	},
	{
		label: "兄弟姐妹",
		value: 3
	},
	{
		label: "祖父母/外祖父母",
		value: 4
	},
	{
		label: "孙子/外孙",
		value: 5
	},
	{
		label: "子女/儿媳",
		value: 6
	},
	{
		label: "其他",
		value: 7
	},
	],
});

// 根据当前选项卡和搜索文本过滤列表
const filteredList = computed(() => {
	const list = currentTab.value === 0 ? state.userList : state.familyList;
	if (!state.searchText) return list;

	return list.filter(item => {
		const searchLower = state.searchText.toLowerCase();
		return item.name.toLowerCase().includes(searchLower) ||
			item.phone.includes(state.searchText);
	});
});




const addMembr = () => {
	uni.navigateTo({
		url: "/pages/addMember/addMember"
	})
}

function logout() {
	uni.removeStorageSync("userid");
	uni.removeStorageSync("phone");
	uni.removeStorageSync("userInfo");
	uni.removeStorageSync("searchUser");
	uni.removeStorageSync("userName");
	uni.navigateTo({
		url: "/pages/index/index",
	});
}

// 切换选项卡
const switchTab = (index) => {
	currentTab.value = index;
	state.searchText = ''; // 清空搜索内容
	if (index === 0) {
		getUserList();
	} else {
		getFamilyList();
	}
};

// 搜索处理（可以添加防抖）
const handleSearch = () => {
	let data = []
	// 这里可以添加防抖处理
	const list = currentTab.value === 0 ? state.userList : state.familyList;
	if (!state.searchText) {
		data = list;
	} else {
		console.log('list', list)
		data = list.filter(item => {
			const searchLower = state.searchText.toLowerCase();
			if (currentTab.value === 0) {
				return item.person_name?.toLowerCase().includes(searchLower) || item.phone?.includes(state
					.searchText);
			} else {
				return item.family_person_name?.toLowerCase().includes(searchLower) || item
					.family_person_phone?.includes(state
						.searchText);
			}

		});
		console.log('data', data, state.searchText)
	}
	state.showData = data



};

// 获取用户列表
const getUserList = async () => {
	// 调用接口获取用户列表
	let submitData = {
		condition: {
			status: 1,
		},
	};
	const res = await request("selectUser", submitData);
	console.log('res', res)
	if (res.status) {
		state.userList = res.result
		state.showData = currentTab.value === 0 ? state.userList : state.familyList;
		state.searchText = ""

	} else {
		uni.showToast({
			title: res.data.msg || "获取家庭成员失败",
			icon: "none",
		});
	}

};

//删除成员
const delMember = async (id) => {
	// 调用接口获取用户列表
	const res = await request("deleteFamily", {
		deleteId: id
	});
	console.log('res', res)
	if (res.status) {
		let familyId = uni.getStorageSync('userid')
		getFamilyList(state.currentFamily)
	} else {
		uni.showToast({
			title: res.data.msg || "删除失败",
			icon: "none",
		});
	}
}


// 获取户籍列表
const getFamilyList = async (userId) => {
	// 调用接口获取户籍列表
	// const userId = state.userId;
	let submitData = {
		condition: {
			belong_user_id: userId,
		},
	};
	state.currentFamily = userId
	const res = await request("selectFamily", submitData);

	if (res.status) {
		state.familyList = res.result.map((member) => ({
			...member,
			offset: 0, // 添加滑动偏移量属性
		}));
		currentTab.value = 1
		uni.setStorageSync('userid', userId)
		state.showData = currentTab.value === 0 ? state.userList : state.familyList;
		state.searchText = ""
	} else {
		uni.showToast({
			title: res.data.msg || "获取家庭成员失败",
			icon: "none",
		});
	}
	// state.familyList = ...
};

//查看积分列表
const toWallet = (item) => {
	let searchUser = item._id
	let name = item.person_name
	uni.setStorageSync('searchUser', searchUser)
	uni.setStorageSync('userName', name)
	uni.navigateTo({
		url: "/pages/wallet/wallet"
	})
}
//查看积分列表
const toRedemption = (id) => {
	uni.navigateTo({
		url: "/pages/redemption/redemption?id=" + id
	})
}
let startX = 0;
let currentIndex = -1;
const deleteWidth = -120; // 修改删除按钮的偏移距离

const touchStart = (e, index) => {
	startX = e.touches[0].clientX;
	currentIndex = index;
};

const touchMove = (e) => {
	if (currentIndex === -1) return;

	const moveX = e.touches[0].clientX - startX;
	let offset = moveX;

	// 限制左滑距离
	if (offset < deleteWidth) {
		offset = deleteWidth;
	}
	// 限制右滑
	if (offset > 0) {
		offset = 0;
	}

	state.familyList[currentIndex].offset = offset;
};
const addMember = () => {
	if (state.familyList.length >= 10) {
		uni.showToast({
			title: `最多只能添加${10}位家人`,
			icon: "none",
		});
		return;
	}

	uni.navigateTo({
		url: "/pages/addMember/addMember",
	});
};

const touchEnd = () => {
	if (currentIndex === -1) return;

	const currentOffset = state.familyList[currentIndex].offset;
	// 如果滑动超过删除按钮宽度的一半，则完全显示删除按钮
	if (currentOffset < deleteWidth / 2) {
		state.familyList[currentIndex].offset = deleteWidth;
	} else {
		state.familyList[currentIndex].offset = 0;
	}

	currentIndex = -1;
};

const initTab = () => {
	currentTab.value = 0
}

onShow(() => {
	console.log(123)
	initTab()
	switchTab(0)
});
</script>

<style lang="scss">
.family-container {
	background: #f5f5f5;
	min-height: 100vh;
	padding-bottom: 200rpx;

	// .tab-header {
	// 	display: flex;
	// 	background: #fff;
	// 	padding: 20rpx 0;
	// 	border-bottom: 1rpx solid #eee;

	// 	.tab-item {
	// 		flex: 1;
	// 		text-align: center;
	// 		font-size: 28rpx;
	// 		color: #666;
	// 		position: relative;
	// 		padding: 20rpx 0;

	// 		&.active {
	// 			color: #ff5555;
	// 			font-weight: bold;

	// 			&::after {
	// 				content: '';
	// 				position: absolute;
	// 				bottom: 0;
	// 				left: 50%;
	// 				transform: translateX(-50%);
	// 				width: 40rpx;
	// 				height: 4rpx;
	// 				background: #ff5555;
	// 				border-radius: 2rpx;
	// 			}
	// 		}
	// 	}
	// }

	.header {
		background-color: #fff;
		padding: 20rpx;
		display: flex;
		justify-content: space-between;
		align-items: center;

		.backBtn {
			margin-right: 10rpx;
			background-color: #bfbfbf;
			border-radius: 10rpx;
			padding: 10rpx 20rpx;
		}
	}

	// 搜索框
	.search-box {
		background-color: #f5f5f5;
		height: 80rpx;
		border-radius: 40rpx;
		display: flex;
		align-items: center;
		padding: 0 30rpx;
		// width: 80%;
		flex: 1;

		.search-icon {
			width: 40rpx;
			height: 40rpx;
			margin-right: 20rpx;
		}



		input {
			flex: 1;
			font-size: 28rpx;
		}

		.placeholder-style {
			color: #999;
		}
	}

	.logout-btn {
		margin-left: 20rpx;
		display: flex;
		align-items: center;

		.logout-icon {
			width: 50rpx;
			height: 50rpx;
			margin-right: 5rpx;
		}


	}

	.body {
		padding: 20rpx;
	}

	.add-member {
		background: #fff;
		border-radius: 12rpx;
		padding: 30rpx;
		display: flex;
		align-items: center;
		margin-bottom: 20rpx;

		.add-icon {
			width: 80rpx;
			height: 80rpx;
			border-radius: 50%;
			border: 2rpx dashed #ff5555;
			color: #ff5555;
			display: flex;
			align-items: center;
			justify-content: center;
			font-size: 40rpx;
			margin-right: 20rpx;
		}

		.add-text {
			.title {
				font-size: 32rpx;
				color: #ff5555;
				margin-bottom: 6rpx;
			}

			.subtitle {
				font-size: 24rpx;
				color: #fa9797;
			}
		}
	}

	.member-list {
		border-radius: 12rpx;
		overflow: hidden;

		.user-item {
			background: #fff;
			margin-bottom: 20rpx;
			padding: 30rpx;
			border-radius: 12rpx;
			display: flex;
			align-items: center;

			.user-avatar {
				position: relative;
				width: 100rpx;
				height: 100rpx;
				margin-right: 30rpx;

				image {
					margin-left: 10px;
					width: 80%;
					height: 80%;
					// border-radius: 50%;
				}

				.gender-icon {
					position: absolute;
					right: -6rpx;
					bottom: -6rpx;
					width: 36rpx;
					height: 36rpx;
					line-height: 36rpx;
					text-align: center;
					background: #fff;
					border-radius: 50%;
					font-size: 24rpx;
					color: #ff5555;
					border: 1rpx solid #ff5555;
				}
			}

			.user-info {
				flex: 1;

				.name {
					font-size: 32rpx;
					color: #333;
					margin-bottom: 10rpx;
				}

				.phone {
					font-size: 28rpx;
					color: #666;
					margin-bottom: 6rpx;
				}

				.address {
					font-size: 24rpx;
					color: #999;
				}
			}

		}

		.member-item {
			background-color: #fff;
			padding: 40rpx 30rpx;
			display: flex;
			align-items: center;
			position: relative;
			margin-bottom: 20rpx;
			box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
			border-radius: 12rpx;
			transition: transform 0.3s ease;

			&:last-child {
				margin-bottom: 0;
			}

			.member-avatar {
				width: 80rpx;
				height: 80rpx;
				background: #eee;
				border-radius: 50%;
				margin-right: 20rpx;
			}

			.member-info {
				flex: 1;
				// padding-left: 120rpx;

				.name {
					font-size: 32rpx;
					color: #333;
					display: inline-block;
					margin-right: 20rpx;
					vertical-align: middle;
				}

				.tag {
					display: inline-block;
					font-size: 24rpx;
					color: #ff5555;
					background: rgba(255, 85, 85, 0.1);
					padding: 2rpx 12rpx;
					border-radius: 4rpx;
					margin-bottom: 6rpx;
					vertical-align: middle;

					&.tag-brother,
					&.tag-mother {
						color: #ff5555;
						background: rgba(255, 85, 85, 0.1);
					}
				}

				.phone {
					font-size: 26rpx;
					color: #999;
				}
			}

			.arrow {
				color: #ccc;
				font-size: 32rpx;
			}

			.delete-btn {
				position: absolute;
				right: -200rpx; // 调整位置，给圆形按钮留出空间
				top: 50%;
				transform: translateY(-50%); // 垂直居中
				width: 150rpx;
				height: 150rpx; // 设置相同的宽高实现圆形
				background: #ff5555;
				color: #fff;
				display: flex;
				align-items: center;
				justify-content: center;
				border-radius: 50%; // 圆形
				font-size: 40rpx;

				.deleteIcon {
					width: 80rpx;
					height: 80rpx;
				}
			}
		}

		.avatar {
			position: relative;
			width: 100rpx;
			height: 100rpx;
			margin-right: 30rpx;

			image {
				width: 100%;
				height: 100%;
				border-radius: 50%;
			}
		}
	}

}

.member-item-Bg {
	background-repeat: no-repeat;
	background-size: 100% 100%;
}

.btnBox {
	margin-right: 10rpx;
	font-size: 26rpx;
	color: #fff;

	.detailBtn {
		padding: 8rpx 12rpx;
		border-radius: 10rpx;
		background-color: #ffa940;
		margin: 8rpx 0;
	}
	
	.redemptionBtn {
		padding: 8rpx 12rpx;
		border-radius: 10rpx;
		background-color: #ff3636;
		margin: 8rpx 0;
	}

	.walltBtn {
		padding: 8rpx 12rpx;
		border-radius: 10rpx;
		background-color: #1890ff;
		margin: 8rpx 0;
	}
}
</style>